package com.shop.mms_client;

import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.Manifest;
import android.content.pm.PackageManager;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;

public class TestActivity extends Activity {
    private static final int PERMISSION_REQUEST_CODE = 123;
    private RadioGroup emulatorGroup;
    private EditText phoneNumberEdit;
    private EditText messageEdit;
    private TextView statusText;
    private String currentEmulator;
    private String pendingPhoneNumber;
    private String pendingMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        // 初始化视图
        initViews();
        
        // 设置默认模拟器
        currentEmulator = "5554";
        
        // 监听模拟器选择
        emulatorGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.emulator5554) {
                currentEmulator = "5554";
                updateReceiverNumber("5556");
            } else {
                currentEmulator = "5556";
                updateReceiverNumber("5554");
            }
            updateStatus();
        });

        // 发送短信按钮
        findViewById(R.id.sendSmsButton).setOnClickListener(v -> checkPermissionAndSendSms());
        
        // 加载测试数据
        findViewById(R.id.loadTestDataButton).setOnClickListener(v -> loadTestData());
        
        // 初始更新状态
        updateStatus();
        updateReceiverNumber("5556");

        // 设置返回按钮点击事件
        findViewById(R.id.backButton).setOnClickListener(v -> onBackPressed());
    }

    private void initViews() {
        emulatorGroup = findViewById(R.id.emulatorGroup);
        phoneNumberEdit = findViewById(R.id.phoneNumberEdit);
        messageEdit = findViewById(R.id.messageEdit);
        statusText = findViewById(R.id.statusText);
    }

    private void updateStatus() {
        String status = String.format("当前模拟器: %s\n发送端口: %s\n",
            currentEmulator,
            "emulator-" + currentEmulator);
        statusText.setText(status);
    }

    private void updateReceiverNumber(String number) {
        phoneNumberEdit.setText(number);
    }

    private void checkPermissionAndSendSms() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS)
                != PackageManager.PERMISSION_GRANTED) {
            // 保存待发送的信息
            pendingPhoneNumber = phoneNumberEdit.getText().toString();
            pendingMessage = messageEdit.getText().toString();
            
            // 请求权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.SEND_SMS},
                    PERMISSION_REQUEST_CODE);
        } else {
            // 已有权限，直接发送
            sendSms();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户授予了权限
                if (pendingPhoneNumber != null && pendingMessage != null) {
                    sendSms();
                }
            } else {
                // 用户拒绝了权限
                Toast.makeText(this, "需要发送短信权限才能测试", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void sendSms() {
        String phoneNumber = phoneNumberEdit.getText().toString();
        String message = messageEdit.getText().toString();

        if (phoneNumber.isEmpty() || message.isEmpty()) {
            Toast.makeText(this, "号码和内容不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(phoneNumber, null, message, null, null);
            Toast.makeText(this, "发送成功", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, "发送失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void loadTestData() {
        ArrayList<String> testMessages = new ArrayList<>();
        testMessages.add("这是一条正常的测试短信。");
        testMessages.add("【垃圾短信】恭喜您中奖了！点击领取 http://fake.url");
        testMessages.add("您的验证码是: 123456，请勿泄露。");
        testMessages.add("【广告】最新优惠活动，详情请访问 www.spam.com");

        int index = (int) (Math.random() * testMessages.size());
        messageEdit.setText(testMessages.get(index));
    }

    @Override
    public void onBackPressed() {
        // 返回主界面
        finish();
    }
} 